﻿using System.CodeDom.Compiler;
using System.Text;
using CVS.DAL;
using Microsoft.CSharp;

namespace Cvs.Compilers
{
    public class CSharpCompiler : ICompiler
    {
        public CompilationResult Compile( string sourceCode, string outputFile)
        {
            var provider = new CSharpCodeProvider();

            var compilerParams = new CompilerParameters
            {
                OutputAssembly = outputFile,
                GenerateInMemory = false,
                GenerateExecutable = true,
                ReferencedAssemblies =
                {
                    @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Core.dll"
                }
            };

            var compilationResult = provider.CompileAssemblyFromSource( compilerParams, sourceCode );

            var compilationOutput = new StringBuilder();
            if ( compilationResult.Output != null )
            {
                for ( int index = 0; index < compilationResult.Errors.Count; index++ )
                {
                    var error = compilationResult.Errors[ index ];
                    compilationOutput.Append( error.ErrorText );
                }
            }

            return new CompilationResult
            {
                IsSuccessful = !compilationResult.Errors.HasErrors,
                Output = compilationOutput.ToString(),
                OutputFile = compilationResult.PathToAssembly
            };
        }
    }
}
